﻿using FileReceiveWeb.Models;
using NLog;
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Http;

namespace FileReceiveWeb.Controllers
{
    public class FileController : ApiController
    {
        public static readonly Logger log = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 问吧传文件到.3 
        /// .3接收后接收文件保存到.2
        /// </summary>
        /// <returns></returns>
        public string PostSaveFile()
        {
            var request = HttpContext.Current.Request;
            var fileCollect = request.Files;
            var fileSize = request.Headers.Get("FileSize");
            string result = "error";
            try
            {
                foreach (string item in fileCollect.AllKeys)
                {
                    HttpPostedFile file = fileCollect[item];
                    string fileName = file.FileName;
                    file.SaveAs(AppSettingConstant.saveToDegbug + file.FileName);
                    log.Info($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}：保存文件{file.FileName}成功");
                    result = "ok";
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
                log.Info($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}:{result}");
            }
            return result;
        }


        /// <summary>
        /// 读取.2的文件上传到问吧服务器
        /// </summary>
        /// <param name="fileName">文件名称 路径加名称 xx/xx.xxx</param>
        /// <returns></returns>
        [HttpGet]
        public string GetReadFileToServer(string fileName)
        {
            string host = @"file:";
            log.Info($"读取.2的文件上传到问吧服务器 文件地址为{host + fileName}");
            try
            {
                WebRequest request = WebRequest.Create(host + fileName);
                WebResponse response = request.GetResponse();
                Stream xmlStream = response.GetResponseStream();
                int index = fileName.LastIndexOf(@"\");
                string xmlName = fileName.Substring(index + 1, fileName.Length - index - 1);
                return UpLoadFile(AppSettingConstant.saveFileApi, xmlStream, xmlName);   
            }
            catch (Exception ex)
            {
                log.Info(ex.Message);
                return ex.Message;
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url">远程上传接口</param>
        /// <param name="filePaht">文件路径</param>
        /// <param name="zipName">文件名称</param>
        /// <returns></returns>
        public string UpLoadFile(string url, Stream fileStream, string zipName)
        {
            string result = string.Empty;
            //边界符  
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            //创建请求
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary; //请求类型
            wr.Method = "POST";
            wr.KeepAlive = true;
            //定义请求流
            Stream rs = wr.GetRequestStream();
            //开始写入
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            // 文件参数头  
            string header = string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type:application/zip\r\n\r\n", zipName);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            //写入文件流
            //FileStream fileStream = new FileStream(filePaht, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[fileStream.Length];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            wr.Headers.Add("FileSize", fileStream.Length.ToString());
            fileStream.Close();

            // 最后的结束符  
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                result = reader2.ReadToEnd();

            }
            catch (WebException ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    result = ex.Message;
                }
            }
            return result.Trim('"');

        }

        
    }
}
